package com.junlaninfo;

import java.util.HashMap;

/**
 * Created by 辉 on 2020/12/7.
 * 第二种：使用数组+链表的方式实现HashMap
 */
public class ExtHashMap<K, V> {
    private Entry[] entrys = new Entry[1000];

    /**
     * 数组+链表方式
     *
     * @param <K>
     * @param <V>
     */
    class Entry<K, V> {
        K k;
        V v;
        Entry<K, V> next;

        public Entry(K k, V v) {
            this.k = k;
            this.v = v;
        }
    }

    public void put(K k, V v) {
        // 数组+链表实现 hash算法
        int index = k == null ? 0 : k.hashCode() % entrys.length;
        // 判断key是否发生冲突
        Entry oldEntry = entrys[index];
        if (oldEntry == null) {
            // key 没有发生hash碰撞的问题
            entrys[index] = new Entry<K, V>(k, v);
        } else {
            oldEntry.next = new Entry<K, V>(k, v);
        }
    }

    public V get(K k) {
        int index = k == null ? 0 : k.hashCode() % entrys.length;
        for (Entry oldEntry = entrys[index]; oldEntry != null; oldEntry = oldEntry.next) {
            if ((k == null && oldEntry.k == null) || oldEntry.k.equals(k)) {
                return (V) oldEntry.v;
            }
        }
        return null;
    }

    public static void main(String[] args) {
        ExtHashMap<Object, Object> extHashMap = new ExtHashMap<Object, Object>();
        extHashMap.put("age",26);
        System.out.println(extHashMap.get("age"));
        HashMap<String, String> map = new HashMap<String, String>();
        map.put(null,null);
    }

}
